import { defineStore } from "pinia";

interface UserInfo {
  id: number;
  username: string;
  role: string;
  avatar?: string;
  permissions?: string[];
}

interface UserState {
  userInfo: UserInfo | null;
  token: string | null;
}

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    userInfo: null,
    token: null
  }),

  getters: {
    isLoggedIn: state => !!state.token,
    isSuperAdmin: state => state.userInfo?.role === "super_admin"
  },

  actions: {
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
    },

    setToken(token: string) {
      this.token = token;
    },

    clearUserInfo() {
      this.userInfo = null;
      this.token = null;
    },

    // 登录
    async login(username: string, password: string) {
      try {
        // TODO: 调用登录接口
        // const { token, userInfo } = await loginApi(username, password);
        const mockResponse = {
          token: "mock_token",
          userInfo: {
            id: 1,
            username: "admin",
            role: "super_admin",
            avatar: "https://example.com/avatar.jpg"
          }
        };

        this.setToken(mockResponse.token);
        this.setUserInfo(mockResponse.userInfo);
        return true;
      } catch (error) {
        return false;
      }
    },

    // 登出
    async logout() {
      try {
        // TODO: 调用登出接口
        this.clearUserInfo();
        return true;
      } catch (error) {
        return false;
      }
    }
  }
});
